<template>
  <view class="like-effect-container" :class="{ liked: isLiked }">
    <view class="trigger-slot-wrapper" @click.stop="handleLikeClick">
      <slot></slot>
    </view>

    <view class="particles-container">
      <view
        v-for="particle in particles"
        :key="particle.id"
        class="particle"
        :style="particle.style"
      >
        <svg class="particle-icon" viewBox="0 0 24 24" :style="{ fill: particle.color }">
          <path
            d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
          />
        </svg>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const isLiked = ref(true)
const particles = ref([])
let particleIdCounter = 0

const emit = defineEmits(['click'])

const handleLikeClick = () => {
  // 切换点赞状态。现在外部可以通过 .liked 类来改变按钮样式
  isLiked.value = !isLiked.value

  // 只有在“点赞”时才创建粒子
  if (isLiked.value) {
    createParticles()
  }
  emit('click')
}

// createParticles 函数与之前完全相同，负责生成粒子数据
function createParticles() {
  const particleCount = 10
  const colors = ['#ffc107', '#ff4757', '#3498db', '#9b59b6', '#2ecc71']

  for (let i = 0; i < particleCount; i++) {
    const id = particleIdCounter++
    const color = colors[Math.floor(Math.random() * colors.length)]

    const size = Math.floor(Math.random() * 41) + 40
    const duration = Math.random() * 1 + 0.8
    const delay = Math.random() * 0.2
    const left = `calc(50% + ${Math.random() * 40 - 20}px)`

    const style = {
      width: `${size}px`,
      height: `${size}px`,
      left,
      animationDuration: `${duration}s`,
      animationDelay: `${delay}s`,
    }

    particles.value.push({ id, style, color })

    setTimeout(
      () => {
        particles.value = particles.value.filter((p) => p.id !== id)
      },
      (duration + delay) * 1000,
    )
  }
}
</script>
<script lang="ts">
export default {
  options: {
    virtualHost: true,
    name: 'KLikeButton',
  },
}
</script>
<style scoped lang="scss">
.like-effect-container {
  position: relative;
  display: inline-flex; /* 使容器尺寸自适应内容 */
}

.trigger-slot-wrapper {
  /* 确保 z-index 比粒子高，这样才能被点击到 */
  position: relative;
  z-index: 10;
  cursor: pointer;
}
/* 粒子相关的样式保持不变，它们是效果的核心 */
.particles-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  /* 粒子从容器的中心底部开始出现 */
  bottom: 50%;
  left: 50%;
  transform: translateX(-50%);
  animation-name: float-up;
  animation-timing-function: ease-out;
  animation-fill-mode: forwards;
}

.particle-icon {
  display: block;
  width: 100%;
  height: 100%;
}

@keyframes float-up {
  0% {
    opacity: 1;
    transform: translate(-50%, 0) scale(1);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -300px) scale(0);
  }
}
</style>
